// -------------------------------------------------------------
// api: user.account.login
// time: 2020-07-18
// author: minner
// -------------------------------------------------------------
exports['user.account.login'] = {
    '1.0': function (args, session, callback) {

        // todo 统一验证入参
        if (!args.user_name || typeof args.user_name != 'string') {
            return callback(11, null, '缺少参数(user_name)');
        }
        if (typeof args.login_password != 'string' || args.login_password.length != 32) {
            return callback(11, null, '缺少参数(login_password)');
        }

        var allow_login_fields = ['mobile', 'email', 'login_name'];
        var login_field_index, lower_case_username = args.user_name.toLowerCase();
        if (args.user_name.length == 11 && !isNaN(args.user_name) && args.user_name * 1 == args.user_name) {
            login_field_index = 0;
        } else if (args.user_name.indexOf('@') > -1) {
            login_field_index = 1;
        } else if (
            uim.commons['isAllowChars'](lower_case_username, 'abcdefghijklmnopqrstuvwxyz_0123456789') && // 登录名只允许使用字母、数字和下划线
            uim.commons['isAllowChars'](lower_case_username.charAt(0), 'abcdefghijklmnopqrstuvwxyz') // 必须以字母开头
        ) {
            login_field_index = 2;
        } else {
            return callback(11, null, '只允许使用手机号、电子邮箱或登录名进行登录');
        }
        var sql_find_admin = 'SELECT * FROM deploy_admin WHERE ' + allow_login_fields[login_field_index] + ' = ' + mysql.escape(args.user_name) + ' LIMIT 1';
        uim.db_query(sql_find_admin, function (err, results, fields) {
            if (err) {
                return callback(6, null, '数据库查询出错：' + err);
            }

            if (!results[0]) {
                return callback(6, null, '登录名不存在');
            }

            if (results[0]['login_password'] == uim.md5('login_password_' + args.login_password)) {
                // 创建会话
                var new_session = {
                    account_id: uim.createSafeString({
                        int_unique: results[0].admin_id,
                        int_tag: uim.config.enum.ACCOUNT_ID,
                    }),
                    // account_id: results[0].admin_id,
                    real_name: results[0].real_name,
                    head_portrait: results[0].head_portrait,
                };
                session.account_id = results[0].admin_id; // 将登录用户账户编辑记录到session的account_id键中
                return callback(0, new_session);
            } else {
                return callback(12, null, '密码错误');
            }

        });
    },

};
